package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 分页查询
    @Override
    public PageDTO<Item> getItemList(int page, int size) {
        IPage<Item> pages = new Page<>(page,size);
        IPage<Item> itemIPage = baseMapper.selectPage(pages, null);
        long total1 = itemIPage.getTotal();
        List<Item> records = itemIPage.getRecords();
        return new PageDTO<>(total1,records);
    }

    //商品上下架
    @Override
    public boolean updateStatus(Long id, Integer tag) {
        Item item = baseMapper.selectById(id);
        item.setStatus(tag);
        baseMapper.updateById(item);

        if(tag == 1){
            rabbitTemplate.convertAndSend("item.topic","item.insert",item);
        }else if(tag == 2){
            rabbitTemplate.convertAndSend("item.topic","item.delete",id);
        }


        return true;
    }

    @Override
    public boolean updateStock(Long id, Integer num) {
        //减少库存
        Item item = baseMapper.selectById(id);
        if(item.getStock() >= num){
            item.setStock(item.getStock() - num);
            baseMapper.updateById(item);
            return true;
        }else{
            return false;
        }
    }
}
